package restaurant.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

/**
 * This panel displays the offers.
 * 
 * @author Odessa
 */
@SuppressWarnings("serial")
public class ViewOffersPanel extends JPanel
{

	/** The this panel. */
	private JPanel thisPanel = this;

	/** The edit button. */
	private JButton editButton;

	/** The offers table. */
	protected JTable offersTable;

	/** The OK button. */
	private JButton okButton;

	/** The table scroll pane. */
	private JScrollPane tablePane;

	/** The offer number. */
	protected int id;

	/** The description of the offer. */
	protected String desc;

	/** The discount of the offer. */
	protected int discount;

	/** The start date of the offer. */
	protected String startDate;

	/** The end date of the offer. */
	protected String endDate;



	/**
	 * The main method.
	 * 
	 * @param args the arguments
	 */
	public static void main(String[] args)
	{
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLayout(new BorderLayout());
		frame.getContentPane().add(new ViewOffersPanel(), BorderLayout.CENTER);
		frame.pack();
		frame.setVisible(true);
	}



	/**
	 * Creates the panel.
	 */
	public ViewOffersPanel() {
		initComponents();

		TableColumnModel model = offersTable.getColumnModel();
		model.removeColumn(offersTable.getColumn("Offer number"));

		ListSelectionModel selectionModel = offersTable.getSelectionModel();
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		selectionModel.addListSelectionListener(new OffersRowListener(this));
	}



	/**
	 * Initializes the components.
	 */
	private void initComponents()
	{

		tablePane = new JScrollPane();
		offersTable = new JTable();
		okButton = new JButton();
		editButton = new JButton();

		offersTable.setModel(new DefaultTableModel(new Object[][] {
				{ null, null, null, null, null },
				{ null, null, null, null, null },
				{ null, null, null, null, null },
				{ null, null, null, null, null },
				{ null, null, null, null, null } }, new String[] {
				"Offer number", "Description", "Discount", "Start date",
				"End date" }) {
			@SuppressWarnings("rawtypes")
			Class[] types = new Class[] { Integer.class, String.class,
					Integer.class, Object.class, Object.class };
			boolean[] canEdit = new boolean[] { false, false, false, false,
					false };



			@SuppressWarnings({ "unchecked", "rawtypes" })
			public Class getColumnClass(int columnIndex)
			{
				return types[columnIndex];
			}



			public boolean isCellEditable(int rowIndex, int columnIndex)
			{
				return canEdit[columnIndex];
			}
		});
		tablePane.setViewportView(offersTable);

		okButton.setText("OK");
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt)
			{
				okButtonActionPerformed(evt);
			}
		});

		editButton.setText("Edit");
		editButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt)
			{
				editButtonActionPerformed(evt);
			}
		});

		GroupLayout layout = new GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGroup(
										layout.createParallelGroup(
												Alignment.TRAILING)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		editButton)
																.addPreferredGap(
																		ComponentPlacement.UNRELATED)
																.addComponent(
																		okButton))
												.addComponent(
														tablePane,
														GroupLayout.PREFERRED_SIZE,
														375,
														GroupLayout.PREFERRED_SIZE))
								.addContainerGap(25, Short.MAX_VALUE)));

		layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {
				editButton, okButton });

		layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addComponent(tablePane,
										GroupLayout.PREFERRED_SIZE, 215,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(okButton)
												.addComponent(editButton))
								.addContainerGap(51, Short.MAX_VALUE)));
	}



	/**
	 * The event handler for the OK button.
	 * 
	 * @param evt the action event.
	 */
	private void okButtonActionPerformed(ActionEvent evt)
	{
		JFrame frame = (JFrame) SwingUtilities.getRoot(thisPanel);
		frame.dispose();
	}



	/**
	 * The event handler for the Edit button.
	 * 
	 * @param evt the action event.
	 */
	private void editButtonActionPerformed(ActionEvent evt)
	{
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		Date start = null, end = null;

		if (desc != null) {
			try {
				start = (Date) formatter.parse(startDate);
				end = (Date) formatter.parse(endDate);
			}
			catch (ParseException pe) {
			}

			Frame frame = new Frame(new OfferPanel(id, start, end, desc,
					discount));
			frame.run();
		}
		else {
			Frame frame = new Frame(new OfferPanel());
			frame.run();
		}
	}

}

/**
 * The event listener class for table. Triggered when a row is selected.
 * 
 * @author Odessa
 */
class OffersRowListener implements ListSelectionListener
{

	ViewOffersPanel row;
	JTable table;



	/**
	 * Creates the RowListenere
	 * 
	 * @param vop the <code>ViewMenuPanel</code>.
	 */
	public OffersRowListener(ViewOffersPanel vop) {
		row = vop;
		table = row.offersTable;
	}



	/**
	 * When the value changes, the row index is retrieved and
	 * <code>getRowValues</code> gets called.
	 * 
	 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
	 */
	@Override
	public void valueChanged(ListSelectionEvent e)
	{
		if (!e.getValueIsAdjusting()) {
			ListSelectionModel model = table.getSelectionModel();
			int index = model.getLeadSelectionIndex();
			getRowValues(index);
		}
	}



	/**
	 * Retrieves the values from the edited row.
	 * 
	 * @param rowIndex the row that was edited.
	 */
	private void getRowValues(int rowIndex)
	{
		try {
			row.id = (Integer) table.getModel().getValueAt(rowIndex, 0);
			row.desc = (String) table.getValueAt(rowIndex, 0);
			row.discount = (Integer) table.getValueAt(rowIndex, 1);
			row.startDate = (String) table.getValueAt(rowIndex, 2);
			row.endDate = (String) table.getValueAt(rowIndex, 3);
		}
		catch (NullPointerException npe) {
			row.id = 0;
			row.desc = null;
			row.discount = 0;
			row.startDate = null;
			row.endDate = null;
		}

		// System.out.println(row.id + ", " +row.desc + ", " +row.discount +
		// ", " + row.startDate + ", " + row.endDate);
	}
}
